const jql = require('jql')
const result = require('result')

//定义联表查询配置
const linkedTableConfig = {
  mainRule: void 0,
  secondRule: void 0,
  mainField: void 0,
  secondField: void 0,
  selectConfig: void 0
}

module.exports = {
  _before() {
  },
  //获取列表数据
  async getList(tableName) {
    return await jql(this, tableName).get()
  },
  //统计条数
  async getCount(tableName, rule = {}) {
    return await jql(this, tableName).where(rule).count()
  },
  //根据字段匹配数据
  async getListByField(tableName, field, value) {
    return await jql(this, tableName).where(`${field} == "${value}"`).get()
  },
  //联表查询
  async getInfoByTwoTable(MainTable, SecondTable, config = linkedTableConfig) {
    //获取配置
    const {mainRule, secondRule, mainField, secondField, selectConfig} = config

    //创建主副对象
    const main = jql(this, MainTable).where(mainRule)
    const second = jql(this, SecondTable).where(secondRule)

    //创建主副临时表（并且指定字段）
    const mainTemp = (mainField ? main.field(mainField) : main).getTemp()
    const secondTemp = (secondField ? second.field(secondField) : second).getTemp()

    //返回联表结果
    return await jql(this, mainTemp, secondTemp).get(selectConfig)
  },
  //根据指定id更改数据
  async updateDataById(tableName, id, data) {
    //判断id是不是数组
    const ids = Array.isArray(id) ? id : [id]
    return await jql(this, tableName).where(`_id in ${JSON.stringify(ids)}`).update(data)
  },
  //根据id删除数据
  async deleteDataById(tableName, ids) {
    return await jql(this, tableName).where(`_id in ${JSON.stringify(ids)}`).remove()
  },
  //根据字段条件删除数据
  async deleteDataByField(tableName, field, value) {
    return await jql(this, tableName).where(`${field} == "${value}"`).remove()
  },
  //新增数据
  async insertData(tableName, data) {
    return await jql(this, tableName).add(data)
  },
  //批处理
  _after(error, res) {
    if (error) throw error

    return result.success(res.data ?? res)
  }
}
